package org.openkoala.demo.facade.impl;


import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.QueryChannelService;
import org.dayatang.utils.Page;
import org.openkoala.demo.application.BookApplication;
import org.openkoala.demo.core.domain.Book;
import org.openkoala.demo.facade.BookFacade;
import org.openkoala.demo.facade.dto.BookDTO;
import org.openkoala.demo.facade.impl.assembler.BookAssembler;

@Named
public class BookFacadeImpl implements BookFacade {

	@Inject
	private BookApplication  application;

	private QueryChannelService queryChannel;

    private QueryChannelService getQueryChannelService(){
       if(queryChannel==null){
          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
       }
     return queryChannel;
    }
	
	public BookDTO getBook(Long id) {
		Book book =application.getBook(id);
		return BookAssembler.EntityToDto(book);
	}
	
	public BookDTO saveBook(BookDTO bookDTO) {
		Book book = new Book();
        book=BookAssembler.DtoToEntity(bookDTO);
		application.saveBook(book );
		bookDTO.setId((java.lang.Long) book.getId());
		return bookDTO;
	}
	
	public void updateBook(BookDTO bookDTO) {
		Book book = Book.get(Book.class, bookDTO.getId());
		application.updateBook(BookAssembler.DtoToEntity(bookDTO));
	}
	
	public void removeBook(Long id) {
			application.removeBook( id );
	}
	
	public void removeBooks(Long[] ids) {
		application.removeBooks( ids) ;
	}
	
	public List<BookDTO> findAllBook() {
		List<BookDTO> list = new ArrayList<BookDTO>();
		List<Book> all = Book.findAll(Book.class);
		for (Book book : all) {
			list.add(BookAssembler.EntityToDto( book));
		}
		return list;
	}
	
	public Page<BookDTO> pageQueryBook(BookDTO queryVo, int currentPage, int pageSize) {
		List<BookDTO> result = new ArrayList<BookDTO>();
		List<Object> conditionVals = new ArrayList<Object>();
	   	StringBuilder jpql = new StringBuilder("select _book from Book _book   where 1=1 ");
	   	if (queryVo.getName() != null && !"".equals(queryVo.getName())) {
	   		jpql.append(" and _book.name like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getName()));
	   	}		
        Page<Book> pages = getQueryChannelService().createJpqlQuery(jpql.toString()).setParameters(conditionVals).setPage(currentPage, pageSize).pagedList();
        for (Book book : pages.getData()) {
           // 将domain转成VO 
                  
         BookDTO bookDTO = BookAssembler.EntityToDto(book);       
                             result.add(bookDTO);
        }
        return new Page<BookDTO>(pages.getStart(), pages.getResultCount(), pageSize, result);
	}
	
	
}
